<template>
  <div>
    <h1>人脸识别</h1>
    <video ref="video" width="640" height="480" autoplay></video>
    <canvas ref="canvas" width="640" height="480"></canvas>
    <el-button>开始拍照</el-button>
  </div>
</template>
<script>
export default {
  data() {
    return { video: null, canvas: null };
  },
  mounted() {
    this.video = this.$refs.video;
    this.canvas = this.$refs.canvas;
    navigator.mediaDevices
      .getUserMedia({ video: true })
      .then((stream) => {
        this.video.srcObject = stream;
        this.video.play();
        this.detectFace();
      })
      .catch((error) => {
        console.error("Error accessing camera:", error);
      });
  },
  methods: {
    detectFace() {
      const video = this.video;
      const canvas = this.canvas;
      const context = canvas.getContext("2d");
      const faceDetector = new window.FaceDetector();
      const drawFace = (faces) => {
        context.clearRect(0, 0, canvas.width, canvas.height);
        faces.forEach((face) => {
          const { x, y, width, height } = face.boundingBox;
          context.strokeStyle = "red";
          context.lineWidth = 2;
          context.strokeRect(x, y, width, height);
        });
      };
      const detect = () => {
        faceDetector
          .detect(video)
          .then((faces) => {
            drawFace(faces);
          })
          .catch((error) => {
            console.error("Error detecting face:", error);
          });
        requestAnimationFrame(detect);
      };
      detect();
    },
  },
};
</script>
<style scoped>
canvas {
  position: absolute;
  top: 0;
  left: 0;
}
</style>
